原生 Javascript 实现(拖拽效果、深拷贝)

通过原生的 onmousedown onmousemoveonmouseup 事件实现元素的拖拽效果

通过递归实现深拷贝

实现拖拽

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#drag {
position: absolute;
top: 100px;
left: 300px;
width: 300px;
height: 200px;
background-color: red;
}
</style>
<script>
window.onload = function () {
let obj
let diffX
let diffY
let drag = document.getElementById('drag')

drag.onmousedown = function (el) {
let e = el || window.event // window.event兼容IE6.7,获得鼠标对象
let target = e.target || e.srcElement // e.srcElement兼容IE,获得当前事件源
diffX = e.clientX - target.offsetLeft // e.clientX为鼠标的水平坐标,target.offsetLeft为该元素左边距版面距离,求得鼠标距元素左边界距离
diffY = e.clientY - target.offsetTop
obj = target
}

document.onmousemove = function (el) {
if (obj) {
let e = el || window.event
let left = e.clientX - diffX // 此时元素左边界距离版面距离
let top = e.clientY - diffY
if (left < 0) left = 0
else if (left > window.offsetWidth - obj.offsetWidth) left = window.offsetWidth - obj.offsetWidth
if (top < 0) top = 0
else if (top > window.offsetHeight - obj.offsetHeight) top = window.offsetHeight - obj.offsetHeight

obj.style.cursor = 'move'
obj.style.left = left + 'px'
obj.style.top = top + 'px'
}
}

document.onmouseup = function (el) {
if (obj) {
obj.style.cursor = ''
}
obj = null
}
}
</script>
</head>

<body>
<div id="drag"></div>
</body>
</html>

实现深拷贝

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function deepClone (data) {
let des = Object.prototype.toString.call(data).substring(8).split('')
des.splice(-1)
let type = des.join('')
let obj
if (type === 'Array') {
obj = []
} else if (type === 'Object') {
obj = {}
} else {
return data
}
if (type === 'Array') {
for (let i = 0; i < data.length; i++) {
obj.push(deepClone(data[i]))
}
} else if (type === 'Object') {
for (let key in data) {
obj[key] = deepClone(data[key])
}
}
return obj
}

console.log(deepClone({ a: 1, b: 2, c: [1, 2, { e: 4 }] })) // { a: 1, b: 2, c: [ 1, 2, { e: 4 } ] }